package com.wd.base;

import android.app.Application;

import com.wd.base.component.AppConfig;
import com.wd.base.component.IAppComponent;
import com.wd.base.util.Logger;

import java.lang.ref.WeakReference;
import java.util.Map;

/**
 * NA<BR>
 *
 * @author w4425
 * @version [V2.0.0, 2021/4/20]
 * @since V2.0.0
 */
public class CommonApi {
    private static WeakReference<Application> weakReference;

    public static void init(Application context) {
        if (weakReference == null) {
            weakReference = new WeakReference<>(context);
        }
        initialize(context);
    }

    /**
     * 各个模块初始化
     *
     * @param app
     */
    private static void initialize(Application app) {
        // 遍历所有的组件的Application类，依次用反射的方式实现组件初始化和注册
        Logger.d("initialize start");
        for (Map.Entry<AppConfig.PAGE_TYPE, String> entry : AppConfig.COMPONENTS.entrySet()) {
            try {
                Logger.i("initialize COMPONENTS = " + entry.getValue());
                Class aClass = Class.forName(entry.getValue());
                Object object = aClass.newInstance();
                // 实例化后，调用各个组件的initialize方法（init会实现组件的注册）
                if (object instanceof IAppComponent) {
                    ((IAppComponent) object).initialize(app);
                }
            } catch (IllegalAccessException e) {
                Logger.w("initialize e = " + e.toString());
            } catch (InstantiationException e) {
                Logger.w("initialize e = " + e.toString());
            } catch (ClassNotFoundException e) {
                Logger.w("initialize e = " + e.toString());
            }
        }
        Logger.d("initialize end");
    }

    public static Application getApplication() {
        return weakReference != null ? weakReference.get() : null;
    }
}
